#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
数据库表监控脚本
每10秒刷新显示fund_nav_detail表和fund_download_status表的统计信息
"""

import os
import sys
import time
from datetime import datetime

# 添加项目路径
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

# 设置Django环境
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'wealth_backend.settings')

try:
    import django  # type: ignore
    django.setup()
    from django.db import connection  # type: ignore
    from django.db import OperationalError  # type: ignore
except ImportError as e:
    print(f"Django导入错误: {e}")
    sys.exit(1)

def clear_screen():
    """清屏"""
    os.system('clear' if os.name == 'posix' else 'cls')

def execute_query(query):
    """执行SQL查询"""
    try:
        with connection.cursor() as cursor:
            cursor.execute(query)
            return cursor.fetchall()
    except OperationalError as e:
        return f"查询错误: {e}"
    except Exception as e:
        return f"未知错误: {e}"

def get_table_stats():
    """获取表统计信息"""
    stats = {}
    
    # fund_nav_detail表统计
    queries = {
        'fund_nav_detail_count': "SELECT COUNT(*) FROM fund_nav_detail",
        'fund_nav_detail_funds': "SELECT COUNT(DISTINCT fund_code) FROM fund_nav_detail",
        'fund_nav_detail_latest': "SELECT fund_code, nav_date, unit_nav, cumulative_nav FROM fund_nav_detail ORDER BY nav_date DESC, id DESC LIMIT 1",
        
        'fund_download_status_count': "SELECT COUNT(*) FROM fund_download_status",
        'fund_download_status_funds': "SELECT COUNT(DISTINCT fund_code) FROM fund_download_status",
        'fund_download_status_latest': "SELECT fund_code, download_status, last_attempt_time, error_message FROM fund_download_status ORDER BY updated_at DESC, id DESC LIMIT 1"
    }
    
    for key, query in queries.items():
        result = execute_query(query)
        stats[key] = result
    
    return stats

def format_latest_record(record, table_name):
    """格式化最新记录显示"""
    if not record or isinstance(record, str):
        return "无数据或查询错误"
    
    if table_name == 'fund_nav_detail':
        if len(record) >= 4:
            return f"基金代码: {record[0]}, 净值日期: {record[1]}, 单位净值: {record[2]}, 累计净值: {record[3]}"
    elif table_name == 'fund_download_status':
        if len(record) >= 4:
            error_msg = record[3] if record[3] else "无"
            return f"基金代码: {record[0]}, 下载状态: {record[1]}, 最后尝试时间: {record[2]}, 错误信息: {error_msg}"
    
    return str(record)

def display_stats(stats):
    """显示统计信息"""
    print("=" * 80)
    print(f"数据库表监控 - {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    print("=" * 80)
    
    # fund_nav_detail表信息
    print("\n📊 fund_nav_detail 表统计:")
    print("-" * 50)
    
    nav_count = stats.get('fund_nav_detail_count', [])
    nav_funds = stats.get('fund_nav_detail_funds', [])
    nav_latest = stats.get('fund_nav_detail_latest', [])
    
    if nav_count and not isinstance(nav_count, str):
        print(f"总记录数: {nav_count[0][0]:,}")
    else:
        print(f"总记录数: 查询失败 - {nav_count}")
    
    if nav_funds and not isinstance(nav_funds, str):
        print(f"基金总数: {nav_funds[0][0]:,}")
    else:
        print(f"基金总数: 查询失败 - {nav_funds}")
    
    if nav_latest and not isinstance(nav_latest, str) and len(nav_latest) > 0:
        print(f"最新记录: {format_latest_record(nav_latest[0], 'fund_nav_detail')}")
    else:
        print(f"最新记录: 查询失败 - {nav_latest}")
    
    # fund_download_status表信息
    print("\n📈 fund_download_status 表统计:")
    print("-" * 50)
    
    status_count = stats.get('fund_download_status_count', [])
    status_funds = stats.get('fund_download_status_funds', [])
    status_latest = stats.get('fund_download_status_latest', [])
    
    if status_count and not isinstance(status_count, str):
        print(f"总记录数: {status_count[0][0]:,}")
    else:
        print(f"总记录数: 查询失败 - {status_count}")
    
    if status_funds and not isinstance(status_funds, str):
        print(f"基金总数: {status_funds[0][0]:,}")
    else:
        print(f"基金总数: 查询失败 - {status_funds}")
    
    if status_latest and not isinstance(status_latest, str) and len(status_latest) > 0:
        print(f"最新记录: {format_latest_record(status_latest[0], 'fund_download_status')}")
    else:
        print(f"最新记录: 查询失败 - {status_latest}")
    
    print("\n" + "=" * 80)
    print("按 Ctrl+C 退出监控")
    print("下次刷新: 10秒后")

def main():
    """主函数"""
    print("启动数据库表监控...")
    print("监控表: fund_nav_detail, fund_download_status")
    print("刷新间隔: 10秒")
    print("\n按 Ctrl+C 退出\n")
    
    try:
        while True:
            clear_screen()
            stats = get_table_stats()
            display_stats(stats)
            time.sleep(10)
    except KeyboardInterrupt:
        print("\n\n监控已停止")
        sys.exit(0)
    except Exception as e:
        print(f"\n\n监控出错: {e}")
        sys.exit(1)

if __name__ == '__main__':
    main()